var express = require('express');
var router = express.Router();
var resultJson = require('../result-json');
var HouseModel = require('../models/House');

var xlsx = require('node-xlsx');
var fs = require('fs');
var path = require('path');

router.get('/aaa.json', function(req, res, next){

    res.send('aasa');
});

router.post('/create.json', function(req, res, next){

    var house = req.body;

    HouseModel.create(house)
        .then(function (result) {

            res.send(resultJson(0));

        })
        .catch(next);

});

router.post('/createList.json', function(req, res, next){

    var list = req.body.list;

    var data = []
    list.forEach((item, i) => {
        if (!item[0] && !item[2] && !item[3] && !item[4]){

        } else {
           data.push({
                number: (item[0]||'').toString(),
                name: (item[1]||'').toString(),
                price: (item[2]||'').toString(),
                amount: (item[3]||'').toString()
            })
        }
    })

    HouseModel.createMany(data)
        .then(function (result) {
            res.send(resultJson(0));
        })
        .catch(next);

});


router.post('/edit.json', function(req, res, next){
    var house = req.body;

    var houseId = house._id;
    
    HouseModel.edit(houseId, house)
        .then(function () {

            res.send(resultJson(0));

        })
        .catch(next);

});

router.get('/getHouseList.json', function(req, res, next){

    var pageNum = req.query.pageNum || 1;
    var pageSize = req.query.pageSize || 20;
    var searchText = req.query.text || '';

    var ops = {
        start: (pageNum-1)*pageSize,
        count: pageSize,
        text: searchText
    }

    HouseModel.getHouses(ops)
        .then(function(result){
            res.send(resultJson(0, {
                list: result[0],
                count: result[1]
            }))
        });    
});

router.post('/exportHouseData.json', function(req, res, next){
    var house = req.body;

    var ops = {
        text: house.text || ''
    }

    HouseModel.getAllHouses(ops)
        .then(function(result){

            let datas = switchXlsxData(result[0])

            let filePath = writeXlsxFile(datas)

            res.send(resultJson(0, {
                list: result[0],
                count: result[1],
                filePath
            }))
        });    

});


router.get('/getHouseById.json', function(req, res, next){
    var houseId = req.query.houseId;
    if (!houseId){
        return res.send(resultJson(5003));
    }

    HouseModel.getHouseById(houseId)
        .then(function(result){

            res.send(resultJson(0, result))

        });    
});


function switchXlsxData(list){
    let data = []

    let headerArr = [];
    for (let key in list[0]){ //表头
        if (key !== '_id' && key !== 'created_at'){
            headerArr.push(key)
        }
    }
    data.push(headerArr)

    list.forEach((item, i) => {
        let itemArr = [];
        for (let key in item){
            if (key !== '_id' && key !== 'created_at'){
                itemArr.push(item[key])
            }
        }

        data.push(itemArr)
    })

    return data;
}

function writeXlsxFile(datas){

    let buffer = xlsx.build([
        {
            name:'sheet1',
            data: datas
        }
    ]);

    const fileName = '刘豪杰.xlsx';
    const filePath = path.resolve(__dirname, '../upload/', fileName)


    fs.writeFileSync(filePath, buffer, {'flag':'w'});

    return fileName;
}

module.exports = router;

